from google.appengine.dist import use_library
use_library('django', '1.2')
import cgi
import yaml
import os
import common
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app
import model
import form
from utils import str_is_not_blank
import logging
class DashboardHandler(common.BaseRequestHandler):
    def _get(self):
        directory = os.path.dirname(__file__)
        path = os.path.join(directory, os.path.join('.', 'index.yaml'))
        logging.info('-----------testing yaml file ..........')
        logging.info(path)
        yload = yaml.load(open(path, 'r'))
        st = yaml.dump(yload)
        logging.info(yload['indexes'][0])
        logging.info('----------')

        projects_query = model.Project.all()
        projects = projects_query.fetch(10)
        self.write_out('dashboard.html', {
                      'projects': projects,
                      'extra': st,
                      })

class MemberHandler(common.BaseRequestHandler):
    def _get(self):
        members_query = model.Member.all()
        members = members_query.fetch(10)
        project_query = model.Project.all()
        projects = project_query.fetch(10)
        self.write_out('members.html', {
                      'members': members,
                      'projects': projects
                      })

class UpdateMemberForm(common.BaseRequestHandler):
    def _post(self):
        id_members = self.request.get_all('member')
        status = self.request.get('status')
        id_project = self.request.get('id_project')
        project = model.Project.get_by_id(long(id_project))
        members = []
        for id_member in id_members:
            member = model.Member.get_by_id(long(id_member))
            query = model.ProjectMember().all()
            query.filter('project = ', project)
            query.filter('member = ', member)
            pm = query.get()
            pm.status = status
            pm.put()
            members.append(member)
        html = self.generate('assign_user.html', {'members': members})
        self.json_response({'html': html})

class ProjectForm(common.BaseRequestHandler):
    def _get(self):
        id = self.request.get('id')
        project_form = None
        project_id = ''
        if str_is_not_blank(id):
            project = model.Project.get_by_id(int(id))
            project_id = project.key().id()
            project_form = form.ProjectForm(instance=project)
        else:
            project_form = form.ProjectForm()
        self.write_out('projectForm.html', {
                      'project_id': project_id,
                      'form': project_form
                      })

    def post(self):
        id = self.request.get('id')
        data = None
        if str_is_not_blank(id):
            project = model.Project.get_by_id(int(id))
            data = form.ProjectForm(data=self.request.POST, instance=project)
        else:
            data = form.ProjectForm(data=self.request.POST)

        if data.is_valid():
            project = data.save(commit=False)
            project.opened_by = users.get_current_user()
            project.put()
            project_backlog = model.ProjectBacklog(name="Project backlog", project=project)
            project_backlog.put()
            self.redirect('/iterations?project_id=' + str(project.key().id()))
        else:
            self.write_out('projectForm.html', {
                          'form': data
                          })

application = webapp.WSGIApplication(
                                     [('/admin', DashboardHandler),
                                     ('/admin/members', MemberHandler),
                                     ('/admin/project_form', ProjectForm),
                                     ('/admin/update_member', UpdateMemberForm)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
